<template>
    <div class="app-container">
        <!-- 操作面板 -->
        <el-card class="operation-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="card-title">班级管理操作</span>
                </div>
            </template>
            
            <!-- 文件操作区域 -->
            <div class="operation-section">
                <div class="section-title">文件操作</div>
                <div class="button-group">
                    <el-upload
                        ref="uploadRef"
                        accept=".xls,.xlsx"
                        action="/api/uploadClass"
                        :on-remove="handleRemove"
                        :on-error="handleError"
                        :on-success="uploadSuccess"
                        :disabled="importBtnDisabled"
                        :file-list="fileList"
                        :auto-upload="false"
                        :limit="1"
                        class="upload-component"
                    >
                        <template #trigger>
                            <el-button type="primary" :icon="UploadFilled">
                                从Excel导入
                            </el-button>
                        </template>
                        <el-button type="success" :loading="loading" @click="submitUpload" :icon="Upload">
                            上传到服务器
                        </el-button>
                    </el-upload>
                    
                    <el-button type="info" @click="downloadTemplate()" :icon="Download">
                        下载模板
                    </el-button>
                    <div class="upload-tip">
                                只能上传xls/xlsx文件，导入新班级后将清空原来的班级，请一次性将本学期班级导入完毕
                    </div>
                </div>
            </div>
            
            <!-- 数据操作区域 -->
            <div class="operation-section">
                <div class="section-title">数据操作</div>
                <div class="button-group">
                    <el-button type="primary" @click="handleAdd" :icon="Plus">
                        新增班级
                    </el-button>
                    <el-button 
                        type="danger" 
                        @click="handleBatchDelete" 
                        :disabled="multipleSelection.length === 0"
                        :icon="Delete"
                    >
                        批量删除 ({{ multipleSelection.length }})
                    </el-button>
                </div>
            </div>
        </el-card>

        <!-- 展示上传后的结果 -->
        <el-table
            v-loading="listLoading"
            :data="paginatedData"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            
            <el-table-column align="center" label="序号" width="60px">
                <template #default="scope">
                    {{ scope.$index + 1 + (currentPage - 1) * pagesize }}
                </template>
            </el-table-column>

            <el-table-column label="班级编号" prop="classNo" align="center">
                <template #default="scope">
                    {{ scope.row.classNo }}
                </template>
            </el-table-column>
            <el-table-column label="班级名" prop="className" align="center">
                <template #default="scope">
                    <span>{{ scope.row.className }}</span>
                </template>
            </el-table-column>
            <el-table-column label="班级人数" prop="size" align="center">
                <template #default="scope">
                    {{ scope.row.size }}
                </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 1rem; margin-left: 0.4rem"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="list.length" 
        >
        </el-pagination>
        
        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="500px"
            :before-close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="班级编号" prop="classNo">
                    <el-input v-model="form.classNo" placeholder="请输入班级编号"></el-input>
                </el-form-item>
                <el-form-item label="班级名称" prop="className">
                    <el-input v-model="form.className" placeholder="请输入班级名称"></el-input>
                </el-form-item>
                <el-form-item label="班级人数" prop="size">
                    <el-input-number v-model="form.size" :min="1" :max="200" placeholder="请输入班级人数"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled, Upload, Download, Plus, Delete } from '@element-plus/icons-vue'; // 引入图标
import axios from 'axios';

const { proxy } = getCurrentInstance(); // 用于访问全局属性，如 $axios

const list = ref([]);
const listLoading = ref(true);
const currentPage = ref(1);
const pagesize = ref(10);
const multipleSelection = ref([]); // 多选数据

const uploadRef = ref(null); // 用于引用 el-upload 组件
const fileList = ref([]);
const loading = ref(false);
const importBtnDisabled = ref(false); // 根据实际逻辑控制是否禁用

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);
const form = ref({
  id: null,
  classNo: '',
  className: '',
  size: 1
});

// 表单验证规则
const rules = {
  classNo: [
    { required: true, message: '请输入班级编号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  size: [
    { required: true, message: '请输入班级人数', trigger: 'blur' },
    { type: 'number', min: 1, max: 200, message: '班级人数必须在 1 到 200 之间', trigger: 'blur' }
  ]
};

const paginatedData = computed(() => {
  // .filter((data) => true) 是多余的，直接用 list.value
  return list.value.slice(
    (currentPage.value - 1) * pagesize.value,
    currentPage.value * pagesize.value
  );
});

const getList = async () => {
  listLoading.value = true;
  try {
    const res = await axios.get("/api/classes/getList", {
      headers: {
        "token": localStorage.getItem("token"),
      },
    });
    list.value = res.data.data;
    if (list.value.length === 0) {
      ElMessage.success("暂无班级");
    }
  } catch (error) {
    console.error('Failed to fetch list:', error);
    ElMessage.error('获取班级列表失败');
  } finally {
    listLoading.value = false;
  }
};

// 下载模板
const downloadTemplate = () => {
  window.location.href = "/api/downloadClass";
};

// 上传成功
const uploadSuccess = (response, file, files) => {
  loading.value = false;
  importBtnDisabled.value = false; // 重置按钮状态
  fileList.value = []; // 清空文件列表
  ElMessage.success(response.message || "上传成功"); // 使用后端返回的message
  getList();
  if (uploadRef.value) {
    uploadRef.value.clearFiles(); // 清除已上传文件列表，避免重复上传
  }
};

const handleRemove = (file, files) => {
  console.log('Remove file:', file);
  fileList.value = files;
};

const handleError = (error, file, files) => {
  loading.value = false;
  importBtnDisabled.value = false; // 重置按钮状态
  ElMessage.error("文件上传失败: " + (error.message || '未知错误'));
  console.error('Upload error:', error);
};

// 提交上传文件事件
const submitUpload = () => {
  if (uploadRef.value) {
    loading.value = true;
    importBtnDisabled.value = true; // 上传时禁用按钮
    uploadRef.value.submit();
  } else {
    ElMessage.warning('请先选择文件');
  }
};

const handleSizeChange = (val) => {
  pagesize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 多选处理
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

// 新增
const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增班级';
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  form.value = { ...row };
  dialogTitle.value = '编辑班级';
  dialogVisible.value = true;
};

// 删除单个
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该班级, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await axios.delete(`/api/classes/delete/${row.id}`, {
      headers: {
        "token": localStorage.getItem("token"),
      },
    });
    
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error(res.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete error:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`此操作将永久删除选中的 ${multipleSelection.value.length} 条记录, 是否继续?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const ids = multipleSelection.value.map(item => item.id);
    const res = await axios.delete('/api/classes/deleteBatch', {
      data: ids,
      headers: {
        "token": localStorage.getItem("token"),
      },
    });
    
    if (res.data.code === 200) {
      ElMessage.success('批量删除成功');
      getList();
      multipleSelection.value = [];
    } else {
      ElMessage.error(res.data.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Batch delete error:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    const isEdit = form.value.id !== null;
    const url = isEdit ? '/api/classes/update' : '/api/classes/add';
    const method = isEdit ? 'put' : 'post';
    
    const res = await axios[method](url, form.value, {
      headers: {
        "token": localStorage.getItem("token"),
      },
    });
    
    if (res.data.code === 200) {
      ElMessage.success(isEdit ? '更新成功' : '新增成功');
      dialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.data.message || (isEdit ? '更新失败' : '新增失败'));
    }
  } catch (error) {
    console.error('Submit error:', error);
    ElMessage.error(isEdit ? '更新失败' : '新增失败');
  }
};

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    classNo: '',
    className: '',
    size: 1
  };
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

onMounted(() => {
  getList();
});

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.operation-section {
  margin-bottom: 20px;
}

.operation-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.upload-component {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.el-button {
  border-radius: 6px;
}

.el-card {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .upload-component {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>